// pages/goodsDetail/goodsDetail.js
const app = getApp();
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request';
import {
  sortToBig,
  noticeNav,
  editTabBar,
} from '../../utils/util'
import moment from '../../utils/moment';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    goodsInfo: '', //商品信息
    goodsId: '', //商品id
    isShare: 0, //是否分享页进来的
    goodsDetailPicList: [], //轮播图
    //选规格-------------------------------------开始
    goodsSpec: {},
    //选规格-------------------------------------结束
    vipInfo: {
      discount: 1,
      levelId: 0
    }, //会员信息
    shoppingCarGoodsList: [],
    saleType: 1, //1外卖，2堂食，3服务员点餐,4门店自取
    orderType: 1, //订单类型：1-外卖，2-堂食，3-服务员点餐,4-自取， 
    deskCode: "", //堂食的卓码
    deskId: "", //堂食的卓码id
    shopInfo: {}, //店铺信息
    isSelectModal: false, //选择分享方式
    showCanvas: false, //画布是否打开
    isFinish: false,
    imagePath: '',
    wxShopConfig: {},
    isPlaceOrder: 0,//是否可以预约下单
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    //是否分享页面
    if (options.isShare) {
      this.setData({
        isShare: options.isShare
      })
    }
    if(options.beid){
      this.setData({
        isShare: 1,
      })
    }
    //桌台
    if (options.deskId) {
      this.setData({
        deskId: options.deskId,
        deskCode: options.deskCode
      })
    }
    //订单类型
    if (options.saleType) {
      this.setData({
        saleType: options.saleType,
        orderType: options.orderType
      })
    }
    if (options.id) {
      this.setData({
        goodsId: options.id,
      })

      //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
      if (app.token == "" || app.token == undefined) {
        app.initLogin().then(res => {
          that.initData()
        }).catch(err => {})
      } else {
        that.initData();
      }
    }
  },

  //初始化数据
  async initData() {
    //获取店铺信息
    await this.getShopInfo();
    //获取商品信息
    await this.getUserBaseInfo();
    this.getGoodsById();
  },
  //空的方法，用来阻止冒泡的
  handmiddle() {},
  //打开选择弹窗
  openSelectModal() {
    this.setData({
      isSelectModal: true,
    })
  },
  //关闭选择弹窗
  hideSelectModal() {
    this.setData({
      isSelectModal: false,
    })
  },
  //关闭画布弹窗
  hideCanvas() {
    this.setData({
      showCanvas: false,
    });
  },
  //保存到相册
  openCanvas() {
    var that = this;
    if (this.data.goodsInfo.thumbUrl == "") {
      wx.showToast({
        title: '无商品图片',
        icon: 'none'
      })
    } else {
      that.setData({
        isSelectModal: false,
      })
      wx.showLoading({
        title: '海报生成中...',
        mask: true,
      })

      that.createNewImg();
    }
  },

  createNewImg() {
    var that = this;
    var wxShopConfig = wx.getStorageSync('shopInfo');
    that.setData({
      wxShopConfig: {
        shopBgUrl: wxShopConfig.shopBgUrl,
        shopName: wxShopConfig.shopName,
      },
      showCanvas: true,
      isFinish: false,
    })
    console.log(this.data.wxShopConfig);
    var goods_img = that.data.goodsInfo.thumbUrl+'?imageView2/1/w/500/h/500';
    var shop_img = wxShopConfig.shopBgUrl;
    var code_img = 'https://wxapp.weilian.city/wx/getGoodsDetailQRcode?beid=' + app.beid + '&goodsId=' + that.data.goodsInfo.id;
    console.log('code_img',code_img)
    console.log('shop_img',shop_img)
    console.log('goods_img',goods_img)
    wx.downloadFile({
      url: code_img,
      success: function (res) {
        //二维码图
        var code_img_d = res.tempFilePath;
        wx.downloadFile({
          url: shop_img,
          success: function (res3) {
            //店铺图片
            shop_img = res3.tempFilePath;
            wx.downloadFile({
              url: goods_img,
              success: function (res) {
                //商品图片
                goods_img = res.tempFilePath
                //画图
                that.drawImg(code_img_d, shop_img, goods_img);
              },
              fail() {
                wx.showToast({
                  title: '商品图片下载失败了...',
                  icon: 'none'
                })
                that.setData({
                  showCanvas: false,
                })
              }
            })
          },
          fail() {
            wx.showToast({
              title: '店铺图片下载失败',
              icon: 'none'
            })
            that.setData({
              showCanvas: false,
            })
          }
        })
      },
      fail() {
        wx.showToast({
          title: '小程序码下载失败',
          icon: 'none'
        })
        that.setData({
          showCanvas: false,
        })
      }
    })

  },
  //方法：
  roundRectPath(ctx, x, y, w, h, r) {
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + w, y, x + w, y + h, r);
    ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r);
    ctx.arcTo(x, y, x + w, y, r);
  },
  drawImg(code_img, shop_img, goods_img) {
    console.log(code_img);
    console.log(shop_img);
    console.log(goods_img);
    var that = this;

    var goods_info = that.data.goodsInfo;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff")
    context.fillRect(0, 0, 300, 430) //填充已填充矩形
    //绘制店铺头像和名字
    var shop_name = that.data.wxShopConfig.shopName;
    context.setFontSize(12);
    context.font = 'normal bold 18px arial,sans-serif'
    context.setFillStyle('#000');
    context.fillText(shop_name, 55, 400);
    context.stroke();
    context.setFontSize(10);
    context.font = 'normal'
    context.setFillStyle('#000');
    context.fillText('给您推荐了一个好东西', 55, 415);
    context.stroke();

    //商品图片绘制
    context.drawImage(goods_img, 0, 0, 300, 300)

    //恢复上文内容，绘制其他

    //绘制名字
    var goods_name = goods_info.goodsName;
    if (goods_name.length > 10) {
      goods_name = goods_name.substring(0, 10) + '...'
    }

    context.setFontSize(16);
    context.setFillStyle('#000');
    context.fillText(goods_name, 10, 325);
    context.stroke();
    //价格绘制
    var goods_price = goods_info.shopPrice;
    context.setFontSize(22);
    context.font = 'normal bold 22px arial,sans-serif'
    context.setFillStyle('#FF0619');
    context.fillText(goods_price, 75, 355);
    context.stroke();
    context.setFontSize(14);
    context.setFillStyle('#FF0619');
    context.setTextAlign('left');
    context.fillText("￥", 60, 355);
    context.stroke();
    //抢购价
    context.setStrokeStyle('#fff');
    context.setFillStyle('#FFCD38')
    that.roundRectPath(context, 10, 335, 45, 23, 5);
    context.fill();
    context.stroke();
    context.setFontSize(12);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.fillText("抢购价", 15, 352);
    context.stroke();
    //提示
    context.setFontSize(12);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.fillText("长按识别购买", 210, 415);
    context.stroke();
    //绘制小程序码二维码
    // 画一个圆形裁剪区域
    let wxCode_width = 85;
    let wxCode_x = 204;
    let wxCode_y = 310;
    context.drawImage(code_img, wxCode_x, wxCode_y, wxCode_width, wxCode_width);


    context.save()
    context.beginPath()
    // 裁剪
    //画一个圆形裁剪区域
    let wxShop_width = 40;
    let wxShop_x = 10;
    let wxShop_y = 380;
    context.arc(wxShop_width / 2 + wxShop_x, wxShop_width / 2 + wxShop_y, wxShop_width / 2, 0, Math.PI * 2, false)
    context.setStrokeStyle('#fff');
    context.clip()
    context.drawImage(shop_img, wxShop_x, wxShop_y, wxShop_width, wxShop_width);
    context.restore()
    //恢复上文内容，绘制其他

    context.draw();
    wx.hideLoading();
    that.setData({
      isFinish: true,
    })

    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          console.log(tempFilePath);
          that.setData({
            imagePath: tempFilePath,
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);

  },
  //保存图片
  saveCanvas() {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: (resS) => {
        console.log(resS)
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        that.setData({
          showCanvas: false,
        });
      },
      fail: (errS) => {
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        })
        that.setData({
          showCanvas: false,
        });
      }
    })

  },
  //返回周几信息
  getweek(e) {
    var week = ['1', '2', '3', '4', '5', '6', '7']
    return week[e - 1]
  },
  //获取店铺信息
  getShopInfo() {
    let that = this;
    return new Promise(function (resolve, reject) {
      getRequest("/api/shop/getShopInfo", {
        beid: app.beid
      }).then(res => {
        wx.setStorageSync('paymentPriority', res.data.data.paymentPriority)
        //如果是关店则不给预约
        if(res.data.data.shopOpen == 1 || res.data.data.openDay == ''){
          that.setData({
            isPlaceOrder:0,
          })
        }else{
          that.setData({
            isPlaceOrder: res.data.data.isPlaceOrder,
          })
        }
        //判断营业时间
        res.data.data.shopOpenTime = false;
        if (res.data.data.openDay != '' && res.data.data.openTimePeriods.length != 0) {
          let openTime = JSON.parse(JSON.stringify(res.data.data.openTimePeriods))
          let openTime2 = []
          let weekDay = that.getweek(moment().format('E'))
          //判断是否跨天
          for (let i = 0; i < openTime.length; i++) {
            if (moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].end).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].begin), 'minutes') < 0) {
              openTime2.push({
                end: '24:00',
                begin: openTime[i].begin
              });
              openTime2.push({
                end: openTime[i].end,
                begin: '00:00'
              });
            } else {
              openTime2.push(openTime[i])
            }
          }
          openTime = openTime2;
          console.log(openTime);
          if (res.data.data.openDay.indexOf(weekDay) != -1) {
            for (let i = 0; i < openTime.length; i++) {
              if (moment(moment().format('YYYY-MM-DD HH:mm')).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].begin), 'minutes') >= 0 && moment(moment().format('YYYY-MM-DD HH:mm')).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTime[i].end), 'minutes') <= 0) {
                res.data.data.shopOpenTime = true;
              }
            }
          }
        }
        if (!res.data.data.shopOpenTime) {
          res.data.data.shopOpen = 1
        }

        that.setData({
          shopInfo: res.data.data,
        })
        app.shopInfo = res.data.data;
        wx.setStorageSync('shopInfo', res.data.data);
        console.log(that.data.shopInfo);
        resolve(res);
      }).catch((err) => {
        reject(err);
        console.log(err)
      });
    })

  },

  //获取个人信息
  getUserBaseInfo() {
    let that = this;
    return new Promise(function (resolve, reject) {
      getRequest("/api/vip/getUserBaseInfo", {
        memberId: app.myInfo.memberId,
      }).then((res) => {
        console.log(res.data.data);
        if (res.data.data != null) {
          if (res.data.data.discountRate * 1 < 10 && res.data.data.discountRate * 1 > 0) {
            that.setData({
              'vipInfo.discount': (res.data.data.discountRate * 0.1).toFixed(2) * 1,
              'vipInfo.levelId': res.data.data.level,
            });
          }
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })
  },

  //返回上一页
  backPage() {
    wx.navigateBack({
      delta: 1
    })
  },

  //返回首页
  goHomePage() {
    wx.switchTab({
      url: '../index/index'
    })
  },

  //修改富文本图片宽度
  formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(options) {
    if (options.from == 'button') {
      this.setData({
        isSelectModal: false,
      })
      return {
        title: options.target.dataset.name,
        imageUrl: options.target.dataset.img,
        path: '/pages/goodsDetail/goodsDetail?isShare=1&&id=' + this.data.goodsId + '&saleType=' + this.data.saleType + "&orderType=" + this.data.orderType + "&deskCode=" + this.data.deskCode + "&deskId=" + this.data.deskId,
        success: (res) => {
          console.log("转发成功", res);
        },
        fail: (res) => {
          console.log("转发失败", res);
        }
      }
    }
  },

  //获取商品详情
  getGoodsById() {
    let that = this;
    wx.showLoading({
      title: '加载中...',
      icon: 'none',
      mask: true,
    })
    getRequest("/api/goods/getFoodDetail", {
      goodsId: that.data.goodsId
    }).then((res) => {
      //富文本
      res.data.data.content = that.formatRichText(res.data.data.content)
      //轮播图页
      let goodsDetailPicList = []
      if (res.data.data.goodsDetailPic != '') {
        goodsDetailPicList = res.data.data.goodsDetailPic.split(',')
      }
      //初始skuId
      res.data.data.skuId = 0;

      //该商品等级
      let vipLevels = res.data.data.vipLevel == '' ? [] : res.data.data.vipLevel.split(",");
      if (vipLevels.includes(that.data.vipInfo.levelId.toString())) {
        res.data.data.isShowVipPrice = true;
      } else {
        res.data.data.isShowVipPrice = false;
      }

      this.setData({
        goodsInfo: res.data.data,
        goodsDetailPicList: goodsDetailPicList,
        shoppingCarGoodsList: app.globalData.cartList,
      });
      console.log(that.data.goodsInfo);
      console.log(that.data.goodsDetailPicList);
      console.log(app.userInfo);
      //判断商品
      this.showAddShoppingCar()
      wx.hideLoading();
    }).catch((err) => {
      wx.hideLoading();
    });
  },

  //打开添加购物车
  showAddShoppingCar() {
    let that = this;
    let data = that.data.goodsInfo;
    data.count = 1;
    //多保存一个价格用于只有属性时商品价格计算
    data.attPrice = data.shopPrice
    //判断是套餐，还是多规格，还是单规格
    if (data.goodsAttrType.length > 0 || data.goodsSpec.length > 0) {
      //选规格
      //默认选中第一个规格，单规格则清空
      if (data.isSku == 0) {
        data.goodsSpec = [];
      } else {
        data.goodsSpec.forEach((item, index) => {
          item.specItem.forEach((item2, index2) => {
            if (index2 == 0) {
              item2.checked = true;
            } else {
              item2.checked = false;
            }
          });
        });
      }
      //初始化属性
      data.goodsAttrType.forEach((item, index) => {
        //判断是否必选
        item.goodsAttr.forEach((item2, index2) => {
          item2.count = 0;
        });
      });
      this.setData({
        goodsSpec: data,
      })
    } else {
      //单规格直接添加
      this.setData({
        goodsSpec: data,
      })
    }
    this.undateAddShoppingData();
  },

  floatPrice(num) {
    if (num) {
      num = parseFloat(num);
      return parseFloat(num.toFixed(2))
    } else return 0;
  },

  //规格点击时
  clickSpecItem(e) {
    let cIndex = e.currentTarget.dataset.index;
    let cIndex2 = e.currentTarget.dataset.index2;
    let data = this.data.goodsSpec;
    data.goodsSpec.forEach((item, index) => {
      item.specItem.forEach((item2, index2) => {
        if (index == cIndex) {
          if (index2 == cIndex2) {
            item2.checked = true;
          } else {
            item2.checked = false;
          }
        }
      });
    });
    data.count = 1;
    this.setData({
      goodsSpec: data,
    })
    this.undateAddShoppingData();
  },

  //规格数量减少时
  onSpecSubGoods() {
    let data = this.data.goodsSpec;
    if (data.count <= 1) {
      return;
    } else {
      data.count -= 1;
    }
    this.setData({
      goodsSpec: data,
    })
    this.undateAddShoppingData();
  },
  //规格数量增加时
  onSpecAddGoods() {
    let data = this.data.goodsSpec;
    console.log(data);
    if (data.isSku == 1) {
      if (data.count >= data.skuStock) {
        wx.showToast({
          title: '无库存',
          icon: "none",
        })
        return;
      }
    } else {
      if (data.count >= data.stock) {
        wx.showToast({
          title: '无库存',
          icon: "none",
        })
        return;
      }
    }

    data.count += 1;

    this.setData({
      goodsSpec: data,
    })
    this.undateAddShoppingData();
  },

  //多规格直接结算或者添加购物车，isNowBuy:是否直接结算
  moreSpecGoodsAddCart(e) {
    let that = this;
    //是否直接结算
    let isNowBuy = e.currentTarget.dataset.isNowBuy;
    //判断是否有必填属性未填
    let haveMust = false;
    //是否存在库存
    let isStock = false; 
    for (let i = 0; i < this.data.goodsSpec.goodsAttrType.length; i++) {
      if (this.data.goodsSpec.goodsAttrType[i].isMustChoice == 1) {
        haveMust = true;
        for (let j = 0; j < this.data.goodsSpec.goodsAttrType[i].goodsAttr.length; j++) {
          if (this.data.goodsSpec.goodsAttrType[i].goodsAttr[j].count > 0) {
            haveMust = false;
          }
        }
        if (haveMust) {
          wx.showToast({
            title: this.data.goodsSpec.goodsAttrType[i].typeName + '未选择',
            icon: 'none'
          })
          return;
        }
      }
    }
    //获取已经选中得属性
    let attrList = [];
    this.data.goodsSpec.goodsAttrType.forEach((item, index) => {
      item.goodsAttr.forEach((item2, index2) => {
        if (item2.count > 0) {
          attrList.push({
            count: item2.count,
            id: item2.attrId,
            price: item2.price,
          });
        }
      });
    });

    //把选择的多规格信息传入购物车
    let goodsMessage = this.data.goodsSpec;
    console.log(goodsMessage);
    //加入购物车
    let shoppingCarGoodsList = this.data.shoppingCarGoodsList;
    this.data.goodsSpec.goodsSku.forEach((item, index) => {
      if ((item.skuName == this.data.goodsSpec.goodsSkuNameStr ) && item.stock == 0) {
        console.log("(item.skuName c",item.skuName ,this.data.goodsSpec.goodsSkuNameStr);
        
        return isStock = true;
      }
    });
    if(isStock){
      wx.showToast({
        title: this.data.goodsSpec.goodsSkuName + "该组合已售罄",
        icon: 'none'
      })
      return 
    }
  
    //是否已经存在
    let isHaveGoods = false;
    if (this.data.goodsInfo.goodsAttrType.length > 0 || this.data.goodsInfo.goodsSpec.length > 0) {
      shoppingCarGoodsList.forEach((item, index) => {
        //商品相等，规格相等，属性相等
        if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId && item.goodsArrIds == goodsMessage.goodsArrIds) {
          item.count += goodsMessage.count;
          isHaveGoods = true;
        }
      });
      //不存在时
      if (!isHaveGoods) {

        shoppingCarGoodsList.push({
          checked: true,
          id: goodsMessage.id,
          attrList: attrList,
          cateId: goodsMessage.goodsCateId,
          count: goodsMessage.count,
          goodsId: goodsMessage.id,
          packageList: [],
          packageListString: JSON.stringify(),
          skuId: goodsMessage.skuId,
          thumbUrl: goodsMessage.thumbUrl,
          goodsName: goodsMessage.goodsName,
          goodsSkuName: goodsMessage.goodsSkuName,
          goodsArrName: goodsMessage.goodsArrName,
          goodsArrIds: goodsMessage.goodsArrIds,
          shopPrice: goodsMessage.shopPrice,
          originPrice: goodsMessage.originPrice,
        });

      }
      //购物车数
      shoppingCarGoodsList.forEach((item, index) => {
        //如果是立即结算把购物车其他商品全部设为非选中
        if (isNowBuy) {
          if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId && item.goodsArrIds == goodsMessage.goodsArrIds) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        }
      });
    } else {
      shoppingCarGoodsList.forEach((item, index) => {
        if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId) {
          item.count += 1;
          isHaveGoods = true;
        }
      });
      //不存在时
      if (!isHaveGoods) {

        shoppingCarGoodsList.push({
          checked: true,
          id: goodsMessage.id,
          attrList: [],
          cateId: goodsMessage.goodsCateId,
          count: goodsMessage.count,
          goodsId: goodsMessage.id,
          packageList: [],
          packageListString: JSON.stringify([]),
          skuId: 0,
          thumbUrl: goodsMessage.thumbUrl,
          goodsName: goodsMessage.goodsName,
          goodsSkuName: "",
          goodsArrName: "",
          goodsArrIds: "",
          shopPrice: goodsMessage.shopPrice,
          originPrice: goodsMessage.originPrice,
        });

      }
      //购物车数
      shoppingCarGoodsList.forEach((item, index) => {
        //如果是立即结算把购物车其他商品全部设为非选中
        if (isNowBuy) {
          if (item.id == goodsMessage.id && item.skuId == goodsMessage.skuId) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        }
      });
    }



    this.setData({
      shoppingCarGoodsList: shoppingCarGoodsList,
    });
    this.countPriceTotal();
    //立即结算直接跳确认订单页
    if (isNowBuy) {
      this.toOrderConfirm();
    } else {
      wx.showToast({
        title: '添加成功',
        icon: 'none',
        duration: 1000,
      })
      setTimeout(function () {
        if (that.data.isShare == 0) {
          that.backPage()
        } else {
          that.goHomePage()
        }
      }, 1000)
    }
  },

  //计算合计
  countPriceTotal() {
    app.globalData.cartList = this.data.shoppingCarGoodsList;
    console.log("购物车", app.globalData.cartList);
  },

  //前往确认订单页
  toOrderConfirm() {
    let that = this;
    //判断店铺是否已经打烊
    if (this.data.shopInfo.shopOpen == 1 && this.data.isPlaceOrder == 0) {
      wx.showToast({
        title: '店铺已打烊',
        icon: 'none'
      })
      return;
    }
    //判断店铺销售方式
    if(that.data.shopInfo.salesType.indexOf(that.data.orderType) == -1){
      let showTitle = "";
      if(that.data.orderType == 1){
        showTitle = "外卖";
      }else if(that.data.orderType == 2){
        showTitle = "堂食";
      }else if(that.data.orderType == 4){
        showTitle = "自取";
      }
      wx.showModal({
        title: '提示',
        content: '店铺暂不支持'+showTitle,
        showCancel: false,
        success (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
      return;
    }
    //购物车保存到全局
    app.globalData.cartList = this.data.shoppingCarGoodsList;
    let goods = [];
    this.data.shoppingCarGoodsList.forEach((item, index) => {
      if (item.checked) {
        goods.push(item);
      }
    });
    if (goods.length == 0) {
      wx.showToast({
        title: '未选择商品',
        icon: 'none'
      })
      return;
    }
    wx.redirectTo({
      url: '../orderConfirm/orderConfirm?saleType=' + this.data.saleType + "&orderType=" + this.data.orderType + "&deskCode=" + this.data.deskCode + "&deskId=" + this.data.deskId,
    })
  },

  //属性选择-----------------------------------------------------开始
  //点击加属性时
  addGoodsAtt(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    //console.log(index1);
    //console.log(index2);
    console.log(this.data.goodsSpec.goodsAttrType[index1]);

    if(this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].isSellOut == 1){
      wx.showToast({
        title: '已沽清',
        icon: 'none',
      })
      return;
    }

    //判断是否是可复选
    if (this.data.goodsSpec.goodsAttrType[index1].childrenSelectType == 1) {
      this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count += 1;
    } else {
      this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count = this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count == 1 ? 0 : 1;
    }
    //判断是否可多选
    if (this.data.goodsSpec.goodsAttrType[index1].multipleChoice == 0) {
      if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count > 0) {
        this.data.goodsSpec.goodsAttrType[index1].goodsAttr.forEach((item3, index3) => {
          if (index3 != index2) {
            item3.count = 0;
          }
        });
      }
    }

    this.setData({
      goodsSpec: this.data.goodsSpec,
    })
    this.undateAddShoppingData();
  },
  //点击减属性时
  subGoodsAtt(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    //console.log(index1);
    //console.log(index2);
    console.log(this.data.goodsSpec.goodsAttrType[index1]);
    if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count <= 0) {
      return;
    }
    this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count -= 1;
    this.setData({
      goodsSpec: this.data.goodsSpec,
    })
    this.undateAddShoppingData();
  },
  //属性选择-----------------------------------------------------结束

  //更新添加购物车的价格和规格文字，选择规格,选择的属性等
  undateAddShoppingData() {
    let data = this.data.goodsSpec;
    let selectIds = [];
    let goodsSkuName = [];
    let goodsSkuNameStr = '';
    console.log(this.data.goodsSpec);
    if (data.isSku == 1) {
      data.goodsSpec.forEach((item, index) => {
        item.specItem.forEach((item2, index2) => {
          if (item2.checked) {
            selectIds.push(item2.id);
            goodsSkuName.push(item2.itemName);
          }
        });
      });
      data.goodsSkuNameStr = goodsSkuName.join("_")
      data.goodsSkuName = '[' + goodsSkuName.join(",") + "]";
      //小到大排序
      let specsId = sortToBig(selectIds).join("_");
      data.goodsSku.forEach((item, index) => {
        if (item.specsId == specsId) {
          data.shopPrice = item.shopPrice * 1;
          data.skuId = item.id;
          data.skuStock = item.stock;
        }
      });
    } else {
      data.shopPrice = data.attPrice
    }
    //计算属性价格
    let attPrice = 0;
    let goodsArrName = "";
    let goodsArrIds = "";
    //console.log(data.goodsAttrType);
    data.goodsAttrType.forEach((item, index) => {
      item.goodsAttr.forEach((item2, index2) => {
        attPrice = attPrice + item2.price * item2.count;
        if (item2.count != 0) {
          if (item2.count == 1) {
            goodsArrName += item2.attrName + ","
          } else {
            goodsArrName += item2.attrName + "*" + item2.count + ","
          }
          goodsArrIds += item2.attrId + "*" + item2.count + ","
        }
      });
    });
    if (goodsArrName != '') {
      data.goodsArrName = goodsArrName.substring(0, goodsArrName.length - 1);
    } else {
      data.goodsArrName = goodsArrName
    }
    //是否显示vip价格
    let discount = 1;
    if (data.isShowVipPrice) {
      discount = this.data.vipInfo.discount;
    }
    data.goodsArrIds = goodsArrIds;
    data.originPrice = this.floatPrice((data.shopPrice * 1 + attPrice));
    data.shopPrice = this.floatPrice((data.shopPrice * 1 + attPrice) * discount);
    //商品价格+属性价格
    this.setData({
      goodsSpec: data,
    })
    console.log(this.data.goodsSpec);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})